package cn.cdu.doctor.controller;

import cn.hutool.core.date.DateUtil;
import cn.cdu.basics.baseVo.PageVo;
import cn.cdu.basics.baseVo.Result;
import cn.cdu.basics.utils.PageUtil;
import cn.cdu.basics.utils.ResultUtil;
import cn.cdu.data.utils.NullUtils;
import cn.cdu.doctor.entity.Doctor;
import cn.cdu.doctor.service.IDoctorService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;


@RestController
@Tag(name = "医生管理")
@RequestMapping("/zwz/doctor")
@Transactional
public class DoctorController {

    @Autowired
    private IDoctorService iDoctorService;

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @Operation(summary = "查询所有医生")
    public Result<List<Doctor>> getAll() {
        return new ResultUtil<List<Doctor>>().setData(iDoctorService.list());
    }

    @RequestMapping(value = "/getByPage", method = RequestMethod.GET)
    @Operation(summary = "查询医生")
    public Result<IPage<Doctor>> getByPage(@ModelAttribute Doctor doctor, @ModelAttribute PageVo page) {
        QueryWrapper<Doctor> qw = new QueryWrapper<>();
        if (!NullUtils.isNull(doctor.getDoctorName())) {
            qw.like("doctor_name", doctor.getDoctorName());
        }
        if (!NullUtils.isNull(doctor.getPostLevel())) {
            qw.eq("post_level", doctor.getPostLevel());
        }
        if (!NullUtils.isNull(doctor.getSubjectId())) {
            qw.eq("subject_id", doctor.getSubjectId());
        }
        if (!NullUtils.isNull(doctor.getNoeDate()) && Objects.equals(doctor.getNoeDate(), "是")) {
            qw.inSql("id", "SELECT id FROM t_doctor WHERE id IN(SELECT DISTINCT doctor_id FROM t_doctor_scheduling WHERE DATE = '" + DateUtil.today() + "')");
        }
        return new ResultUtil<IPage<Doctor>>().setData(iDoctorService.page(PageUtil.initMpPage(page), qw));
    }

    @RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST)
    @Operation(summary = "增改医生")
    public Result<Doctor> saveOrUpdate(Doctor doctor) {
        if (iDoctorService.saveOrUpdate(doctor)) {
            return new ResultUtil<Doctor>().setData(doctor);
        }
        return ResultUtil.error();
    }

    @RequestMapping(value = "/delByIds", method = RequestMethod.POST)
    @Operation(summary = "删除医生")
    public Result<Object> delAllByIds(@RequestParam String[] ids) {
        for (String id : ids) {
            iDoctorService.removeById(id);
        }
        return ResultUtil.success();
    }
}
